/*   
 * File    : tb_8b10b_noise.v
 * Purpose : Error detection test for 8b10b-code encoder and decoder*              
 * Author  : Golovchenko Aleksey
 * Date    : 2012/12/25
 */

`timescale 1ns / 1ns
module test_8b10b;

    reg [8:0] testin;
    reg dispin;    

    reg [9:0] decodein;
    reg decdispin;
   
    wire [9:0] 	testout;
    wire dispout, decodedisp, decodeerr, disperr;
    wire [8:0] 	decodeout;
    
    encode enc_inst(testin, dispin, testout, dispout);
    decode dec_inst(decodein, decdispin, decodeout, decodedisp, decodeerr, disperr);

    reg[8:0] i;
    integer log_file;

    // Генерирование последовательности входных данных
    initial begin
        $dumpfile("tb8b10b_noise.vcd");
        $dumpvars(1, testin, dispin, dispout, testout);
        $dumpvars(1, decodein, decdispin, decodedisp, decodeout);                
        $dumpvars(1, disperr, decodeerr);

        log_file = $fopen("tb8b10b_noise.log", "w");

        decdispin = 0;
        dispin = 0;
      
        // Подаем на вход кодера целые числа  
        for (i=0; i<30; i=i+1) begin                    
           testin = i;
           
           #1
           dispin = dispout;
        end            
    end 

    always @ (decodedisp) begin
        #1
        decdispin = decodedisp;
    end

    // Внесение искажений в сигнал
    integer seed = 2000;    
    integer bit_idx;
    reg [9:0] channel;
    always @ (testin) begin
        channel = testout;

        // Искажаем бит в одном из 10 битов
        if ({$random(seed)}%3 == 0 && i > 0) begin
            bit_idx = {$random(seed)}%10;

            channel[bit_idx] = ~channel[bit_idx];
            
            // $display("%d ns : add error in bit %d\n", $time, bit_idx);
            $fwrite(log_file, "%-5d ns : add error in bit %-4d\n", $time, bit_idx);
        end

        decodein = channel;        
        decdispin = decodedisp;
    end
    
endmodule
